<?php

namespace app\api\model;

use think\Cache;
use app\common\model\dealer\Order as OrderModel;
use app\api\controller\command\Dealer as commandDealer;

/**
 * 分销 模型
 * Class Spec
 * @package app\api\model
 */
class Dealer extends OrderModel
{

    /**
     * 获取榜单数据
     * @param $type string 榜单类型
     * @param $force bool 是否强制刷新缓存
     * @return array|object
     * @throws \app\common\exception\BaseException
     * @throws \think\exception\DbException
     */
    public function getRankData($type,$force=false)
    {
        if (!$force && $rankData = Cache::get("{$type}_CacheDealRank")) {
            return $rankData;
        }else{//重新获取并缓存榜单数据
            if($type=='team'){  //团队总推荐用户排行（显示前100名） 显示每个人伞下单数的总和
                $commandDealer = new commandDealer();
                $data = $commandDealer->saveDealerRankData(1);
            }else{
                if($type=='week'){  //本周
                    $sTime = mktime(0, 0, 0, date('m'), (date('d') - (date('w')>0 ? date('w') : 7) + 1), date('Y'));
                    $limit = 30;
                    $expire = 600;// 缓存时间10分钟
                }elseif($type=='month'){  //本月
                    $sTime = mktime(0, 0, 0, date('m'), 1, date('Y'));
                    $limit = 50;
                    $expire = 1800;// 缓存时间30分钟
                }else{//总推荐用户
                    $limit = 100;
                    $expire = 3600;// 缓存时间1小时
                }

                if(isset($sTime) && !empty($sTime)) $this->where('d_order.create_time', '>=', $sTime);
                $this->where('d_order.order_type', '=', 10);//普通订单
                $this->where('order.pay_status', '=', 20);//已付款
                $data = $this->alias('d_order')
                    ->field('count(d_order.id) as counts,user.nickName,user.avatarUrl')
                    ->join('order', 'order.order_id = d_order.order_id')
                    ->join('dealer_user', 'dealer_user.user_id = d_order.first_user_id')
                    ->join('user', 'dealer_user.user_id = user.user_id')
                    ->order(['counts' => 'desc'])
                    ->group("d_order.first_user_id")
                    ->limit($limit)
                    ->select();

                if(!empty($data)) Cache::set("{$type}_CacheDealRank", $data, $expire);
            }

            return $data;
        }
    }


}
